package com.xbjtech.vipsystem.shiro;

import com.alibaba.fastjson.JSON;
import com.xbjtech.vipsystem.vo.Result;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.authc.AuthenticationFilter;
import org.apache.shiro.web.util.WebUtils;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;

/**
 * @author leejun.happy@gmail.com
 * @created 2019-07-23
 */
public class JwtFilter extends AuthenticationFilter {


    private AuthenticationToken createToken(ServletRequest req, ServletResponse response) {
        HttpServletRequest request = WebUtils.toHttp(req);
        String token = request.getHeader("X-TOKEN");
        if (token == null) {
            return null;
        }
        return new JwtToken(token);
    }

    @Override
    protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) {
        /**
         * "/login" => handler
         * "/user/list" => 认证处理
         */
        if (this.isLoginRequest(request, response)) {
            return true;
        }
        AuthenticationToken token = createToken(request, response);
        if (token == null) {
            return false;
        }
        try {
            Subject subject = getSubject(request, response);
            subject.login(token);
            return true;
        } catch (AuthenticationException e) {
            return false;
        }
    }

    @Override
    protected boolean onAccessDenied(ServletRequest request, ServletResponse resp) throws Exception {
        // 进行登录异常处理，不是很完善，待处理
        // 要么没有token
        // 要么登陆失败
        HttpServletResponse response = WebUtils.toHttp(resp);
        Result<String> result = Result.fail("操作失败，请稍候再试");
        String json = JSON.toJSONString(result);
        response.setContentType("application/json;charset=UTF-8");
        PrintWriter writer = response.getWriter();
        writer.print(json);
        return false;
    }

}
